#include<iostream>
#include<string>
#include<unistd.h>
#include<cstdio>
#include"Thread.hpp"
#include"LockGuard.hpp"
int ticket=10000;

std::string GetThreadName()
{
    static int num=1;
    char buffer[64];
    snprintf(buffer,sizeof(buffer),"Thread - %d",num++);
    return buffer;
}

void GetTicket(ThreadData*td)
{
    while(true)
    {
    LockGuard lockguard(td->_mutex);
    //pthread_mutex_lock(td->_mutex);
    if(ticket>0)
    {
        //sleep(1);
        printf("%s get a ticket %d\n" ,td->_threadname.c_str(),ticket--);
    //    pthread_mutex_unlock(td->_mutex);
    }
    else 
    {
    //    pthread_mutex_unlock(td->_mutex);
        break;
    }
    }
}

int main()
{
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex,nullptr);
    std::string threadname=GetThreadName();
    ThreadData*d1=new ThreadData(threadname,&mutex);
    Thread* td=new Thread(threadname,GetTicket,d1);
     std::string threadname2=GetThreadName();
    ThreadData*d2=new ThreadData(threadname2,&mutex);
    Thread* td2=new Thread(threadname2,GetTicket,d2);
    std::string threadname3=GetThreadName();
    ThreadData*d3=new ThreadData(threadname3,&mutex);
    Thread* td3=new Thread(threadname3,GetTicket,d3);
    td->Start();
    td2->Start();
    td3->Start();
    
    td->Join();
    td2->Join();
    td3->Join();
    
        delete td;
    delete td2;
    delete td3;


    pthread_mutex_destroy(&mutex);
    return 0;
    
}